// 文件内容由脚本自动分发 修改无效

// import 'url-search-params-polyfill'
import axios from 'axios'
// import qs from 'qs'
// import { MessageBox } from 'mx-ui'
import { ElMessageBox } from 'element-plus'
import * as constants from './constants'
// import profile from '@root/profile'
import useAppStore from '@/store/useAppStore'
// import useLayoutStore from '@/store/useLayoutStore'
import { isNullable, omit, sleep } from 'sf-utils2'
import profile from '@root/profile'

// axios.defaults.paramsSerializer = (params) => qs.stringify(params, { arrayFormat: 'repeat' })
// profile.IS_PRO  true为生产环境， false为本地环境
axios.defaults.baseURL = profile.IS_PRO ? '' : ''

// if(process.env.NODE_ENV === "development") axios.defaults.baseURL = '/'

// zabbixMenu
axios.defaults.withCredentials = true // 无需使用cookie

let _requestNum = 0 // 发起请求次数
let _loadingStartTime = null // 加载开始时间戳
let _loadingDuration = 200 // 最小loading加载间隔
let _appStore = null // app store
// let layoutStore = null // layout store

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    _appStore ||= useAppStore()
    const header = {
      'Content-Type': 'application/json',
      ...config.headers,
      [constants.ACCESS_TOKEN]: _appStore?.token,
      common: config.headers?.common
    }
    return {
      ...config,
      headers: omit(header, isNullable),
      params: config?.params
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

let IS_HAS_ALERT = false // 是否弹框
axios.interceptors.response.use(
  (response) => {
    const { data, config } = response || {}
    const pathName = config?.url?.split?.('?')?.at?.(0) || config?.url

    const whiteApis = []
    // 如果存在过滤的白名单接口
    if (whiteApis.includes(pathName)) return response
    switch (data?.code) {
      case 2004:
      case 2013:
      case 2002:
      case 2017:
      case 2001:
      case 2040: {
        !IS_HAS_ALERT &&
          ElMessageBox.alert(data?.message, '提示', {
            type: 'error',
            confirmButtonText: '确定',
            callback: () => {
              IS_HAS_ALERT = false
              _appStore ||= useAppStore()
              _appStore.loginOut(0)
            }
          })
        IS_HAS_ALERT = true
        return Promise.reject(response)
      }
      default: {
        break
      }
    }
    return response
  },
  (error) => {
    console.log(error)
    if (!IS_HAS_ALERT) {
      IS_HAS_ALERT = true
      if (error.response) {
        switch (error.response.status) {
          case 404:
            ElMessageBox.alert(
              `后端接口未找到：${error.response?.data.path}`,
              `${error.response?.status} /(ㄒoㄒ)/~~`
            ).then(() => {
              IS_HAS_ALERT = false
            })
            break
          case 500:
            ElMessageBox.alert('后端网络挂啦！', `${error.response?.status} /(ㄒoㄒ)/~~`).then(() => {
              IS_HAS_ALERT = false
            })
            break
          default:
            ElMessageBox.alert(
              `${error.response?.data.error}：${error.response?.data.path}`,
              error.response?.status,
              error.response?.data?.msg
            ).then(() => {
              IS_HAS_ALERT = false
            })
        }
      } else {
        IS_HAS_ALERT = true
        ElMessageBox.alert('网络连接错误', '网络错误 /(ㄒoㄒ)/~~', {
          type: 'error',
          confirmButtonText: '确定'
        })
      }
    }
    return Promise.reject(error?.response?.data || error)
  }
)

// download 垃圾代码 标记
export const download = (url, fileName, fileType, data, headers = {}, params) => {
  return new Promise((resolve, reject) => {
    axios({
      url,
      params,
      method: constants.POST,
      data,
      headers,
      responseType: 'blob'
    })
      .then((response) => {
        let blob = new Blob([response.data], { type: `${fileType};charset=utf-8` })
        // 获取heads中的filename文件名
        let downloadElement = document.createElement('a')
        // 创建下载的链接
        let href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        // 下载后文件名
        downloadElement.download = fileName
        document.body.appendChild(downloadElement)
        // 点击下载
        downloadElement.click()
        // 下载完成移除元素
        if (document.body.contains(downloadElement)) {
          document.body.removeChild(downloadElement)
        }
        // 释放掉blob对象
        window.URL.revokeObjectURL(href)
        resolve(response.data)
      })
      .catch((rej) => {
        console.log('rej---', rej)
        return reject(rej)
      })
  })
}

// get请求
export const get = (url, params, headers = {}) => {
  return new Promise((res, rej) => {
    axios({ url, method: constants.GET, params, headers })
      .then((response) => {
        res(response.data)
      })
      .catch(rej)
  })
}

// delete
export const del = (url, data, headers = {}, params) => {
  return new Promise((res, rej) => {
    axios({ url, method: constants.DELETE, params, data, headers })
      .then((response) => {
        res(response.data)
      })
      .catch(rej)
  })
}

/**
 * 常规获取文件
 * @param {string} url
 * @param {object} options
 */
export const axiosFactory = (url, options = {}) => {
  // layoutStore ||= useLayoutStore()
  return new Promise((resolve, reject) => {
    _requestNum === 0 && (_loadingStartTime = Date.now())
    _requestNum++
    // layoutStore.loading = true
    axios({ url, method: constants.POST, ...options })
      .then((response) => {
        _requestNum--
        // if (response?.data?.code == 500) {
        //   Message.error(response?.data?.message || '网络异常（500）')
        //   return resolve(undefined)
        // }
        return resolve(response.data)
      })
      .catch((err) => {
        _requestNum--
        return reject(err)
      })
      .finally(async () => {
        if (_requestNum === 0) {
          // 防止闪烁
          const nowTime = Date.now()
          const diff = _loadingDuration - (nowTime - _loadingStartTime)
          if (diff > 0) {
            await sleep(diff + 16)
          }
          // layoutStore.loading = false
        }
      })
  })
}

// post2请求 附加loading
export const postLoading = (url, data, headers = {}, params) => {
  // layoutStore ||= useLayoutStore()
  return new Promise((resolve, reject) => {
    _requestNum === 0 && (_loadingStartTime = Date.now())
    _requestNum++
    // layoutStore.xhrLoading = true
    axios({ url, params, method: constants.POST, data, headers })
      .then((response) => {
        _requestNum--
        resolve(response.data)
      })
      .catch((err) => {
        _requestNum--
        reject(err)
      })
      .finally(async () => {
        if (_requestNum === 0) {
          // 防止闪烁
          const nowTime = Date.now()
          const diff = _loadingDuration - (nowTime - _loadingStartTime)
          if (diff > 0) {
            await sleep(diff + 16)
          }
          // layoutStore.xhrLoading = false
        }
      })
  })
}

// post请求
export const post = postLoading

// post请求 没有loading
export const postNoLoading = (url, data, headers = {}, params) => {
  return new Promise((resolve, reject) => {
    axios({ url, params, method: constants.POST, data, headers })
      .then((response) => {
        resolve(response.data)
      })
      .catch(reject)
  })
}

// put请求
export const put = (url, data, headers = {}, params) => {
  return new Promise((res, rej) => {
    axios({ url, params, method: constants.PUT, data, headers })
      .then((response) => {
        res(response.data)
      })
      .catch(rej)
  })
}

/**
 * 校验code
 * @param {object} response
 * @return {boolean}
 */
export const validateCode = (response) => {
  let result = true
  if (!response?.code) return result
  switch (response?.code) {
    case 2004:
    case 2013:
    case 2002:
    case 2017:
    case 2001:
    case 2040: {
      result = false
      !IS_HAS_ALERT &&
        ElMessageBox.alert(response?.message, '提示', {
          type: 'error',
          confirmButtonText: '确定',
          callback: () => {
            alert(100)
            _appStore ||= useAppStore()
            _appStore.loginOut(0)
            window.reload()
          }
        })
    }
  }
  return result
}
